import time

from appium.webdriver.webdriver import WebDriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput
from selenium.webdriver.remote.webelement import WebElement

from base.exception_handle import app_exception_handle
from base.log_util import logger


class BasePage(object):
    def __init__(self, driver: WebDriver = None):
        self.driver = driver

    @app_exception_handle
    def search_element(self, loc, timeout=10, poll_frequency=0.5) -> WebElement:
        """
        定位单个元素
        :param loc: （By.ID,'属性名'）。。。
        :param timeout: 显示等待事件
        :param poll_frequency: 显示等待搜索间隔
        :return:
        """
        return self.driver.find_element(*loc)

    def search_and_click(self, loc):
        logger.info(f"查找元素：{loc}，然后点击：")
        self.search_element(loc).click()

    def search_and_input(self, loc, text):
        logger.info(f"查找元素：{loc}，然后输入内容：{text}")
        self.search_element(loc).send_keys(text)

    def search_and_gettext(self, loc):
        logger.info(f"查找元素：{loc}，然后获取text：")
        return self.search_element(loc).text

    def move_to_ele(self, loc):
        ele = self.search_element(loc)
        actions = ActionChains(self.driver)
        actions.w3c_actions = ActionBuilder(
            self.driver,
            mouse=PointerInput(interaction.POINTER_TOUCH, "touch")
        )
        actions.w3c_actions.pointer_action.move_to(ele)

    # 定义一个封装滑屏操作的方法
    def slide_screen(self, direction, count=1):
        w = self.driver.get_window_size()["width"]  # 获取手机屏幕的宽度
        h = self.driver.get_window_size()["height"]  # 获取手机屏幕的高度
        # w=1080  h=1920
        if direction == "up":  # 往上滑
            zb = (w / 2, h * 0.9, w / 2, h * 0.1)
        elif direction == "down":  # 往下滑
            zb = (w / 2, h * 0.1, w / 2, h * 0.9)
        elif direction == 'left':  # 往左滑
            zb = (w * 0.9, h / 2, w * 0.1, h / 2)
        elif direction == 'right':  # 往右滑
            zb = (w * 0.1, h / 2, w * 0.9, h / 2)
        else:
            print("无法识别滑动方向，请重新输入！")
        for i in range(count):
            self.driver.swipe(*zb, duration=1200)
            time.sleep(1)